<template>
  <div class="pagestyle">
    <div class="addBox" v-if="addShow">
      <stepcom :stepNum="stepNum"></stepcom>
      <div v-if="stepNum == 1" style="text-align: center; height: 64vh;width: 500px;margin: 80px auto;">
        <el-form ref="ruleFormRef" :model="addForm" :rules="state.formListrules" label-width="auto">
          <el-form-item label="设置组合断电名称" prop="combinationPowerOutageName">
            <el-input v-model="addForm.combinationPowerOutageName" placeholder="请输入" />
          </el-form-item>
          <!-- <el-form-item label="新增断电类型" prop="cutElectricityType">
            <el-select style="width: 100%;" v-model="addForm.cutElectricityType" placeholder="请选择">
              <el-option v-for="item in ['组合断电','瓦斯突出断电']" :label="item" :value="item" />
            </el-select>
          </el-form-item> -->
        </el-form>
        <div class="btnSubmit">
          <el-button type="info" @click="stepNumClick(9,false)">取消</el-button>
          <el-button type="primary" @click="stepNumClick(2, true)">下一步</el-button>
        </div>
      </div>
      <div v-if="stepNum == 2" style="margin-top: 40px">
        <p class="p_title">查询测点</p>
        <div style="
            background: rgba(91, 109, 128, 0.04);
            margin: 0 10px;
            padding: 10px;
          ">
          <querybox :queryList="state.querystwo" @query="queryClick"></querybox>
          <vxe-grid ref="gridRef" v-bind="{
          columnConfig: {
              resizable: true
          },
          border: true,
          showOverflow: true,
          height: 200,
          loading: false,
          scrollY: {
            enabled: true,
            gt: 0
          },
          columns: [
            { type: 'seq', title: '序号', width: 100 },
            { field: 'code', title: '测点编号', minWidth: 180 },
            { field: 'name', title: '名称', minWidth: 180 },
            { field: 'place', title: '地点', minWidth: 180 },
            { title: '操作', slots: { default: 'action' } }
          ],
          data:state.listAnalog
          }">
            <template #action="{ row,rowIndex }">
              <span style="font-size: 14px;color: #409eff;cursor: pointer;" @click="selectClick(row,rowIndex)">选择</span>
            </template>
          </vxe-grid>
        </div>
        <p class="p_title">已选因子({{ state.yinziList.length }})</p>
        <yincard :gaojiBtnShow="true" :cardList="state.yinziList" :biaodaList="state.biaodaList" :listAnalog="state.listAnalog"></yincard>
        <div class="btnSubmit">
          <el-button type="info" @click="stepNumClick(1, false)">上一步</el-button>
          <el-button type="primary" @click="stepNumClick(3, false)">下一步</el-button>
        </div>
      </div>
      <div v-if="stepNum == 3">
        <p class="p_title">已选因子({{ state.yinziList.length }})</p>
        <div style="
            background: rgba(91, 109, 128, 0.04);
            margin: 0 10px;
            padding: 10px;
          ">
          <vxe-table height="200" :data="state.yinziList" border="inner">
            <vxe-column type="seq" :width="55" title="序号"></vxe-column>
            <vxe-column field="code" title="测点编号"></vxe-column>
            <vxe-column field="name" title="名称"></vxe-column>
            <vxe-column field="place" title="地点"></vxe-column>
            <vxe-column field="cutModel" title="断电模式">
              <template #default="{ row }">
                <span style="font-size: 12px; color: red">*</span>
                <el-select style="margin-left: 4px; width: 90%" clearable filterable v-model="row.cutModel"
                  placeholder="请选择" @change="cutModelChange($event, row)">
                  <el-option v-for="item in state.cutModelList" :key="item" :label="item" :value="item">
                  </el-option>
                </el-select>
              </template>
            </vxe-column>
            <vxe-column field="upperCutValue" title="上限断电值">
              <template #default="{ row }">
                <span style="font-size: 12px; color: red" v-show="
                    row.cutModel == '上限断电' || row.cutModel == '上下限断电'
                      ? true
                      : false
                  ">*</span>
                <el-input style="margin-left: 4px; width: 90%" :disabled="
                    row.cutModel == '上限断电' || row.cutModel == '上下限断电'
                      ? false
                      : true
                  " v-model="row.upperCutValue" placeholder="请输入">
                </el-input>
              </template>
            </vxe-column>
            <vxe-column field="upperComplexValue" title="上限复电值">
              <template #default="{ row }">
                <span style="font-size: 12px; color: red" v-show="
                    row.cutModel == '上限断电' || row.cutModel == '上下限断电'
                      ? true
                      : false
                  ">*</span>
                <el-input style="margin-left: 4px; width: 90%" :disabled="
                    row.cutModel == '上限断电' || row.cutModel == '上下限断电'
                      ? false
                      : true
                  " v-model="row.upperComplexValue" placeholder="请输入">
                </el-input>
              </template>
            </vxe-column>
            <vxe-column field="lowerCutValue" title="下限断电值">
              <template #default="{ row }">
                <span style="font-size: 12px; color: red" v-show="
                    row.cutModel == '下限断电' || row.cutModel == '上下限断电'
                      ? true
                      : false
                  ">*</span>
                <el-input style="margin-left: 4px; width: 90%" :disabled="
                    row.cutModel == '下限断电' || row.cutModel == '上下限断电'
                      ? false
                      : true
                  " v-model="row.lowerCutValue" placeholder="请输入">
                </el-input>
              </template>
            </vxe-column>
            <vxe-column field="lowerComplexValue" title="下限复电值">
              <template #default="{ row }">
                <span style="font-size: 12px; color: red" v-show="
                    row.cutModel == '下限断电' || row.cutModel == '上下限断电'
                      ? true
                      : false
                  ">*</span>
                <el-input style="margin-left: 4px; width: 90%" :disabled="
                    row.cutModel == '下限断电' || row.cutModel == '上下限断电'
                      ? false
                      : true
                  " v-model="row.lowerComplexValue" placeholder="请输入">
                </el-input>
              </template>
            </vxe-column>
            <vxe-column field="powerOffConnection" title="断线断电">
              <template #default="{ row }">
                <span style="font-size: 12px; color: red">*</span>
                <el-switch v-model="row.powerOffConnection" />
              </template>
            </vxe-column>
            <vxe-column title="操作" :min-width="80">
              <template #default="{ row }">
                <el-button type="text" @click="selectHBClick(row)">选择</el-button>
                <el-button type="text" @click="removeHBClick(row)">移除</el-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <yunsuanfu :biaodaList="state.biaodaList" :yinziList="state.yinziListHB" @threeStep="threeStep"
          :expression="state.expression">
        </yunsuanfu>
        <p class="p_title">控制口</p>
        <div style="
            background: rgba(91, 109, 128, 0.04);
            margin: 0 10px;
            padding: 10px;
          ">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="分站号" prop="stationNumber">
                <el-select clearable filterable v-model="addForm.stationNumber" @change="stationNumberChange"
                  placeholder="请选择">
                  <el-option v-for="item in state.stationmodelList" :key="item.value" :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button type="info" @click="qingkongClick">清空</el-button>
            </el-col>
            <el-col :span="24">
              <el-checkbox-group v-model="addForm.controlPort" @change="checkboxChange">
                <el-checkbox v-for="item in state.controlPortList"
                  @change="(checked) => handleSingleChange(checked, item)" :label="item" :value="item" />
              </el-checkbox-group>
            </el-col>
            <el-col :span="24">
              <el-input :rows="3" v-model="addForm.combinationCutDto.expression" type="textarea" placeholder="请输入">
              </el-input>
            </el-col>
            <el-col :span="24">
              <el-checkbox v-model="addForm.situation" label="子条件都正常才解除" size="large" />
            </el-col>
          </el-row>
        </div>
        <p class="p_title">馈电条件</p>
        <div class="remarkBox">
          <el-form-item label="馈电条件" prop="feedCondition">
            <el-select multiple clearable filterable v-model="addForm.feedCondition" placeholder="请选择">
              <el-option v-for="item in state.listSensorPointsList" :key="item.code" :label="item.name"
                :value="item.code">
                <span>{{ item.code+'-'+item.place }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <p>备注</p>
          <el-input :rows="3" v-model="addForm.remark" type="textarea" placeholder="请输入">
          </el-input>
        </div>
        <div class="btnSubmit">
          <el-button type="info" @click="stepNumClick(2, false)">上一步</el-button>
          <el-button type="primary" @click="stepNumClick(4, false)">保存</el-button>
        </div>
      </div>
    </div>
    <list_controller ref="zujianname" :options="state.options" v-else :noprintDownShow="true">
      <template v-slot:opraCurdBtnlist="row">
        <span>
          <el-button class="tableFontSize" type="primary" link size="small" @click="editBtn(row.row.row)">编辑
          </el-button>
          <el-button class="tableFontSize" type="primary" link size="small" @click="deleteBtn(row.row.row)">删除
          </el-button>
        </span>
      </template>
      <template v-slot:opraCurdBtnAll>
        <span :class="addShow ? 'listInfoBtn active' : 'listInfoBtn'" @click="addBtn('mul')">
          <svg-icon :class="addShow ? 'active' : ''" class-name="search-icon" icon-class="xinzeng" />
          新增
        </span>
        <span :class="'listInfoBtn'" @click="deleteBtn('mul')">
          <svg-icon class-name="search-icon" icon-class="shanchu" />
          删除
        </span>
      </template>
      <template v-slot:selectNamelist> 组合断电配置 </template>
    </list_controller>
  </div>
</template>
<script setup>
  import list_controller from "@/components/commonCom/list_controller";
  import querybox from "@/components/commonCom/querybox";
  import stepcom from "./zuheCom/stepcom";
  import onestep from "./zuheCom/onestep";
  import yincard from "./zuheCom/yincard";
  import yunsuanfu from "./zuheCom/yunsuanfu";

  import {
    computed,
    reactive
  } from "vue";
  import {
    ElMessage,
    ElMessageBox
  } from "element-plus";
  import {
    table_headers
  } from "@/components/commonCom/table_headers";
  import axios from "@/utils/request";
  import usePagesStore from "@/store/modules/pages";
  import {
    getlistAnalogs,
    getlistSitesList,
    getoutagelistSensorPoints,
  } from "@/api/config";
  import _ from "lodash";
  const {
    proxy
  } = getCurrentInstance();
  const store = usePagesStore();
  const router = useRouter();
  let previewHttps =
    import.meta.env.VITE_APP_HTTP;
  const oneStepRef = ref(null);
  const stepNum = ref(1);
  const addForm = ref({
    status: "A",
  });
  const addShow = ref(false);
  const yinziList = ref([]);
  const editId = ref(undefined);
  let state = reactive({
    controlPortList: [1, 2, 3, 4, 5, 6],
    expressStr: [],
    expressStrString: [],
    expressStrString1: [],
    expressStrList: [],
    stepNum: 1,
    modalTitle: "因子高级配置",
    addModal: false,
    addShow: true,
    biaodaList: [{
        name: "与",
        sub: "&&",
      },
      {
        name: "或",
        sub: "||",
      },
      {
        name: "左括号",
        sub: "(",
      },
      {
        name: "右括号",
        sub: ")",
      },
      {
        name: "撤",
        sub: "销",
      },
      {
        name: "清",
        sub: "空",
      },
    ],
    querystwo: [{
        field: "pointId",
        title: "测点",
        type: "input",
        binddata: "",
      },
      {
        field: "placeName",
        title: "安装地点",
        type: "input",
        binddata: "",
      },
    ],
    listAnalog: [],
    options: {
      tableheads: computed(() => table_headers.configPowerOutage),
      queryList: {
        dropdownUrl: "",
        querys: [],
        queryMap: new Map([
          ["sensorTypeId", "safety_pointType"],
          ["deviceTypeId", "safety_deviceType"],
          ["alarmTypeId", "alarmType"],
        ]),
      },
      dataUrl: "/power/outage/list",
      delUrl: "/power/outage/del",
      addUrl: "/power/outage/add",
      descUrl: "/power/outage/getById",
      editUrl: "/power/outage/modify",
    },
    formList: {},
    formListrules: {
      combinationPowerOutageName: [{
        required: true,
        message: "请输入",
        trigger: "blur",
      }, ],
      cutElectricityType: [{
        required: true,
        message: "请选择",
        trigger: "change",
      }, ],
    },
    addForm: {
      status: "A",
    },
    yinziList: [],
    yinziListHB: [],
    expression: [],
    editId: undefined,
    stationmodelList: [],
    listSensorPointsList: [],
    cutModelList: ["上限断电", "下限断电", "上下限断电"],
    expressStrString2: []
  });

  function addBtn() {
    addShow.value = true;
    editId.value = undefined;
    addForm.value.combinationPowerOutageName = undefined
    addForm.value.cutElectricityType = undefined
  }

  async function editBtn(row) {
    stepNum.value = 1;
    editId.value = row.id;
    addShow.value = true;
    await axios
      .post(state.options.descUrl, {
        id: row.id,
      })
      .then((res) => {
        let data = []
        addForm.value = res.data;
        res.data.combinationCutDto.controlList.forEach(itemsub => {
          if(itemsub.controlPointDtoList){
            itemsub.controlPointDtoList.forEach(itemc => {
              data.push(Number(itemsub.stationCode) + '.' + itemc.controlPoint)
            })
          }
        })
        state.expressStrString1 = data
        state.stationmodelList.forEach(item => {
          if (res.data.combinationCutDto.controlList.length > 0) {
            res.data.combinationCutDto.controlList.forEach(itemsub => {
              if (Number(item.value) == Number(itemsub.stationCode)) {
                item.e = itemsub.controlPointDtoList.map(iteme => {
                  return Number(iteme.controlPoint)
                })
              }
            })
          }
        })
        if (res.data.combinationCutDto.controlList.length > 0) {
          addForm.value.stationNumber = res.data.combinationCutDto.controlList[0].stationCode
          addForm.value.controlPort = res.data.combinationCutDto.controlList[0].controlPointDtoList.map(item => {
            return Number(item.controlPoint)
          })
        }
        // state.yinziList = res.data.pointDtoList;
        let arr = [];
        let arr1 = [];
        res.data.pointDtoList.forEach((item) => {
          item.title = item.code + "/" + item.name;
          item.objarr = [{
              left: "编号",
              right: item.code,
            },
            {
              left: "名称",
              right: item.code + "/" + item.name,
            },
            {
              left: "位置",
              right: item.place,
            },
          ];
           if (!item.marker) {
            arr.push(item);
          }else{
             arr1.push(item)
          }
        });
        state.expression = res.data.expression;
        state.yinziListHB = arr;
        state.yinziList=arr1
         yinziList.value = arr1;
        if (res.data.feedCondition != '') {
          addForm.value.feedCondition = res.data.feedCondition.split(",");
        }
      });
  }


  function threeStep(list) {
    addForm.value.expression = list.expression;
    addForm.value.pointDtoList = []
    let arr1=JSON.parse(JSON.stringify(state.yinziList))
    let arr2=JSON.parse(JSON.stringify(state.yinziListHB))
    arr1.forEach(item=>{
      item.marker = true
    })
    arr2.forEach(item=>{
      item.marker = false
    })
    addForm.value.pointDtoList=arr1.concat(arr2)
    // addForm.value.pointDtoList = _.uniqBy(state.yinziList, "code");
  }

  function stepNumClick(type, state) {
    if (type == 2&&state) {
      proxy.$refs["ruleFormRef"].validate((valid, fields) => {
        if (valid) {
          stepNum.value = type;
        } else {
          stepNum.value = 1;
        }
      })
    } else {
      if (type == 3) {
        if (yinziList.value.length == 0) {
          ElMessage.warning("请先选择测点因子");
        } else {
          stepNum.value = type;
        }
      } else {
        stepNum.value = type;
      }
      if (type == 4) {
        if (addForm.value.expression) {
          addForm.value.status = "B";
          if(addForm.value.controlPort){
            addForm.value.controlPort = addForm.value.controlPort.toString();
          }
          if(addForm.value.feedCondition){
            addForm.value.feedCondition = addForm.value.feedCondition.toString();
          }
          if (editId.value) {
            addForm.value.id = editId.value;
            axios
              .post("power/outage/modify", addForm.value)
              .then((res) => {
                addShow.value = false;
                if (res.code == 200) {
                  ElMessage.success(res.data);
                }
              })
              .catch((err) => {
                stepNum.value = 3;
              });
          } else {
            axios
              .post("power/outage/add", addForm.value)
              .then((res) => {
                addShow.value = false;
                if (res.code == 200) {
                  ElMessage.success(res.data);
                }
              })
              .catch((err) => {
                stepNum.value = 3;
              });
          }
        } else {
          stepNum.value = 3
          ElMessage.warning('请填入公式!')
        }
      }
      if (type == 9) {
        addShow.value = false
        // state.formData = {}
        stepNum.value = 1
        state.yinziList = []
        state.yinziListHB = []
        state.expression = ''
      }
    }
  }

  function getlistAnalogsData() {
    let data = {};
    state.querystwo.forEach((item) => {
      data[item.field] = item.binddata;
    });
    getlistAnalogs(data).then((res) => {
      state.listAnalog = res.data;
      console.log(state.listAnalog, 'state.listAnalog');

    });
    getlistSitesList().then((res) => {
      state.stationmodelList = Object.keys(res.data).map((item) => {
        return {
          label: item + "-" + res.data[item],
          value: item,
          controlPortList: [1, 2, 3, 4, 5, 6]
        };
      });
    });
    getoutagelistSensorPoints({}).then((res) => {
      state.listSensorPointsList = res.data;
    });
  }

  function queryClick(type) {
    let data = {};
    if (type == 2) {
      state.querystwo.forEach((item) => {
        data[item.field] = "";
      });
    }
    getlistAnalogsData();
  }

  function selectClick(row, index) {
    row.title = row.code + "/" + row.name;
    row.objarr = [{
        left: "编号",
        right: row.code,
      },
      {
        left: "名称",
        right: row.code + "/" + row.name,
      },
      {
        left: "位置",
        right: row.place,
      },
    ];
    state.yinziList.push(row);
    yinziList.value = state.yinziList;
    state.listAnalog.splice(index, 1)
  }

  function selectHBClick(row) {
    state.yinziListHB.push(row);
  }

  function removeHBClick(code) {
    state.yinziList = _.pullAllWith(state.yinziList, [code], _.isEqual);
    state.yinziListHB = _.pullAllWith(state.yinziListHB, [code], _.isEqual);
  }

  function deleteBtn(row) {
    let ids = [];
    if (row != "mul") {
      ids = [row.id];
    } else {
      if (store.records.length > 0) {
        ids = store.records.map((item) => {
          return item.id;
        });
      } else {
        proxy.$modal.msgSuccess("请先勾选所要删除数据!");
      }
    }
    if (ids.length > 0) {
      ElMessageBox.confirm(
          '确定要删除该数据吗?',
          '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        .then(() => {
          axios.post(state.options.delUrl, ids).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              state.addModal = false
              ElMessage({
                type: 'success',
                message: res.msg,
              })
              store.records = []
            }
          })

        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '删除取消',
          })
        })
    }
  }
  addForm.value.combinationCutDto = {
    expression: '',
    controlList: []
  }

  function stationNumberChange(e) {
    state.stationmodelList.forEach(item => {
      if (e == item.value) {
        state.controlPortList = item.controlPortList
        addForm.value.controlPort = item.e
        addForm.value.combinationCutDto.controlList.push({
          stationCode: e,
          controlPointDtoList: []
        })
      }
    })
  }

  // 单个复选框选中取消事件
  function handleSingleChange(checked, item) {
    if (!checked) {
      state.expressStrString1 = state.expressStrString1.filter(itemt => itemt !== Number(addForm.value.stationNumber) +
        '.' + item)
    } else {
      state.expressStrString1.push(Number(addForm.value.stationNumber) + '.' + item)
    }
    addForm.value.combinationCutDto.expression = state.expressStrString1.join('&')

  }

  function checkboxChange(e) {
    state.stationmodelList.forEach(item => {
      if (addForm.value.stationNumber == item.value) {
        item.e = e
      }
    })
    addForm.value.combinationCutDto.controlList.forEach(itemsub => {
      if (itemsub.stationCode == addForm.value.stationNumber) {
        itemsub.controlPointDtoList = e.map(iteme => {
          return {
            controlPoint: iteme,
            fragment: Number(addForm.value.stationNumber) + '.' + iteme
          }
        })
      }
    })
    addForm.value.combinationCutDto.controlList = _.uniqBy(addForm.value.combinationCutDto.controlList, "stationCode")

  }

  function cutModelChange() {

  }
  getlistAnalogsData();
  // 控制口清空按钮
  function qingkongClick() {
    state.stationmodelList.forEach(item => {
      item.e = []
    })
    addForm.value.stationNumber = undefined
    addForm.value.controlPort = []
    state.expressStrString1 = []
    addForm.value.combinationCutDto.expression = undefined
  }
</script>
<style lang="scss" scoped>
  .p_title {
    font-size: 16px;
    font-weight: 700;
    padding: 0 10px;
  }

  .pagestyle {
    overflow-y: auto;

    .addBox {
      padding: 42px 0;
      border-radius: 8px;
      background: rgba(255, 255, 255, 0.8);
    }

    .remarkBox {
      padding: 10px;
      font-size: 14px;
    }

    .btnSubmit {
      margin-top: 40px;
      text-align: center;
    }
  }
</style>